<script setup name="HomeSearch">
import useSiteSearchStore from '../../store/hooks/useSiteSearchStore'
import { navTo } from '../../utils/nav'

const site_search_store = useSiteSearchStore()
const cate_index = ref(0)

const links = computed(() => {
  let link = site_search_store.search_config[cate_index.value]
  if (link) {
    return link?.links || []
  }
  return site_search_store.search_config[0]?.links || []
})

const link_index = ref(0)
const handleClickLink = (link_id) => {
  const index = links.value?.findIndex(r => r.id === link_id)
  if (link_index.value === index) return
  if (index >= 0) {
    cur_link.value = 0
    link_index.value = index
  }
}
const cur_link = computed(() => {
  const cur_obj = links.value[link_index.value]
  if (cur_obj) return cur_obj
  return links.value[0] || {}
})

const k = ref('')
const handleSearch = () => {
  const url = cur_link.value.link.replaceAll('[kw]', encodeURIComponent(k.value))
  navTo(url)
}

</script>

<template>
  <div class="search mt-5 mb-5">
    <div class="search-text-top mb-3 flex justify-center items-center space-x-3 text-lg">
      <a
        v-for="(item, index) in site_search_store.search_config"
        :key="index"
        href="#"
        class="search-cate-item"
        :class="{ active: cate_index === index }"
        @click="cate_index = index"
      >
        <span>{{ item.name }}</span>
        <span class="triangle"></span>
      </a>
    </div>
    <div v-show="links" class="search-text-bottom">
      <nav class="flex justify-center items-center space-x-3 text-lg">
        <a
          v-for="(link, index) in links"
          :key="index"
          href="#"
          class="search-link-item"
          :class="{ active: link_index === index }"
          @click.prevent="handleClickLink(link.id)"
        >{{ link.name }}</a>
      </nav>
    </div>
    <div class="search-box mt-5 w-full flex justify-center">
      <div class="search-wrap relative w-full sm:w-1/3 overflow-hidden">
        <input
          v-model="k"
          type="text"
          class="outline-none flex items-center pl-6 pr-14 py-2 rounded-3xl w-full bg-gray-900 bg-opacity-40 hover:bg-opacity-50 transition-all"
          :placeholder="cur_link?.placeholder"
          @keyup.enter="handleSearch"
        />
        <div class="absolute top-0 right-0 pr-4 py-2 hover:text-red-500" @click="handleSearch">
          <app-icon class="text-2xl transition-all" icon="akar-icons:search"></app-icon>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.search-link-item {
  &.active {
    @apply font-extrabold;
  }
}
.search-cate-item {
  @apply flex flex-col items-center;
  &.active {
    .triangle {
      @apply opacity-100;
    }
  }
  .triangle {
    @apply z-10 block mt-0.5 w-0 h-1.5 text-center opacity-0 transition-all;

    border-top: 0.3rem solid var(--site-text-color);
    border-right: 0.3rem solid transparent;
    border-left: 0.3rem solid transparent;
  }
}
</style>
